package com.ruoyi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.*;
import com.ruoyi.mapper.*;
import com.ruoyi.service.IHhOrderDetailService;
import com.ruoyi.utils.ParamsDictUtil;
import com.ruoyi.utils.PrintPageUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售订单明细Service业务层处理
 * @author chongjin
 * @date 2020-11-18
 */
@Service
public class HhOrderDetailServiceImpl implements IHhOrderDetailService {

    private Logger log = LoggerFactory.getLogger(HhOrderDetailServiceImpl.class);

    @Autowired
    private HhOrderDetailMapper hhOrderDetailMapper;
    @Autowired
    private HhUserAccountMapper hhUserAccountMapper;
    @Autowired
    private HhProductMapper hhProductMapper;
    @Autowired
    private HhOrderMapper hhOrderMapper;
    @Autowired
    private HhUserMapper hhUserMapper;

    /**
     * 查询销售订单明细
     * @param odId 销售订单明细ID
     * @return 销售订单明细
     */
    @Override
    public HhOrderDetail selectHhOrderDetailById(Long odId) {
        return hhOrderDetailMapper.selectHhOrderDetailById(odId);
    }

    /**
     * 查询销售订单明细列表
     * @param hhOrderDetailVO 查询参数
     * @return 销售订单明细
     */
    @Override
    public List<HhOrderDetailVO> selectHhOrderDetailList(HhOrderDetailVO hhOrderDetailVO) {
        return hhOrderDetailMapper.selectHhOrderDetailVOList(hhOrderDetailVO);
    }

    /**
     * 新增销售订单明细
     * @param hhOrderDetailVO 销售订单明细
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertHhOrderDetail(HhOrderDetailVO hhOrderDetailVO) {
        int successCount = 0;
        if (StringUtils.isBlank(hhOrderDetailVO.getProductData())) {
            //判断单价是否纯数字
            String productPrice = hhOrderDetailVO.getProductPrice();
            BigDecimal totalPrice = new BigDecimal(productPrice.matches(ParamsDictUtil.MONEY_REGEX) ? productPrice : "0");
            totalPrice = totalPrice.multiply(new BigDecimal(hhOrderDetailVO.getProductNum())).setScale(2, RoundingMode.HALF_UP);
            hhOrderDetailVO.setDetailPrice(productPrice);
            hhOrderDetailVO.setDetailAmount(totalPrice.toString());
            hhOrderDetailVO.setCreateTime(DateUtils.getNowDate());
            hhOrderDetailMapper.insertHhOrderDetail(hhOrderDetailVO);
            //增加权重
            hhProductMapper.updateSelectCount(hhOrderDetailVO.getProductId());
            successCount++;
        } else {
            List<HhOrderDetailVO> hhOrderDetailVOS = JSONObject.parseArray(hhOrderDetailVO.getProductData(), HhOrderDetailVO.class);
            for (HhOrderDetailVO hhOrderDetail : hhOrderDetailVOS) {
                hhOrderDetail.setOrderId(hhOrderDetailVO.getOrderId());
                hhOrderDetail.setDetailPrice(hhOrderDetail.getProductPrice());
                hhOrderDetail.setDetailAmount(hhOrderDetail.getProductPrice());
                hhOrderDetail.setProductNum("1");
                hhOrderDetail.setCreateTime(DateUtils.getNowDate());
                hhOrderDetailMapper.insertHhOrderDetail(hhOrderDetail);
                //增加权重
                hhProductMapper.updateSelectCount(hhOrderDetail.getProductId());
                successCount++;
            }
        }
        return successCount;
    }

    /**
     * 修改销售订单明细
     * @param hhOrderDetail 销售订单明细
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateHhOrderDetail(HhOrderDetail hhOrderDetail) {
        if (StringUtils.isNotBlank(hhOrderDetail.getDetailPrice()) || StringUtils.isNotBlank(hhOrderDetail.getProductNum())) {
            //单价或数量变化
            BigDecimal detailPrice = null;
            if (hhOrderDetail.getDetailPrice().matches(ParamsDictUtil.MONEY_REGEX)) {
                detailPrice = new BigDecimal(hhOrderDetail.getDetailPrice());
                hhOrderDetail.setDetailPrice(detailPrice.setScale(2, RoundingMode.HALF_UP).toString());
            } else {
                detailPrice = new BigDecimal("0");
            }
            BigDecimal detailAmount = detailPrice.multiply(new BigDecimal(hhOrderDetail.getProductNum())).setScale(2, RoundingMode.HALF_UP);
            hhOrderDetail.setDetailAmount(detailAmount.toString());
        }
        hhOrderDetail.setUpdateTime(DateUtils.getNowDate());
        return hhOrderDetailMapper.updateHhOrderDetail(hhOrderDetail);
    }

    /**
     * 删除销售订单明细对象
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteHhOrderDetailByIds(String ids) {
        return hhOrderDetailMapper.deleteHhOrderDetailByIds(Convert.toStrArray(ids));
    }

    /**
     * 保存订单信息
     * @param hhOrderDetailVO 订单参数
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveOrderDetail(HhOrderDetailVO hhOrderDetailVO) {
        //查询明细
        List<HhOrderDetailVO> list = hhOrderDetailMapper.selectHhOrderDetailVOList(hhOrderDetailVO);
        BigDecimal totalMoney = new BigDecimal("0");
        for (HhOrderDetailVO hhOrderDetail : list) {
            totalMoney = totalMoney.add(new BigDecimal(hhOrderDetail.getDetailAmount()));
        }
        //查询订单，修改总额
        HhOrder hhOrder = hhOrderMapper.selectHhOrderById(hhOrderDetailVO.getOrderId());
        hhOrder.setTotalMoney(totalMoney.setScale(2, RoundingMode.HALF_UP).toString());
        return hhOrderMapper.updateHhOrder(hhOrder);
    }

    /**
     * 打印订单信息
     * @param orderId 订单id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map orderPrint(String orderId) {
        log.info("===============打印日志 start==============");
        Map resultMap = new HashMap();
        //查找打印信息
        HhOrderDetailVO hhOrderDetailVO = new HhOrderDetailVO();
        hhOrderDetailVO.setOrderId(orderId);
        List<HhOrderDetailVO> list = hhOrderDetailMapper.selectHhOrderDetailVOList(hhOrderDetailVO);
        //查找订单
        HhOrder hhOrder = hhOrderMapper.selectHhOrderById(orderId);
        String orderType = hhOrder.getOrderType();
        if (StringUtils.isBlank(hhOrder.getPhoneNumber())) {
            hhOrder.setPhoneNumber(hhUserMapper.selectHhUserById(hhOrder.getWorkerId()).getPhonenumber());
        }
        log.info("===========订单信息======" + JSON.toJSON(hhOrder).toString());
        if (StringUtils.equals(ParamsDictUtil.ORDER_STATUS_EDIT, hhOrder.getOrderStatus())) {
            //订单状态为未打印
            //更新订单状态
            BigDecimal totalMoney = BigDecimal.ZERO;
            for (HhOrderDetailVO hhOrderDetail : list) {
                totalMoney = totalMoney.add(new BigDecimal(hhOrderDetail.getDetailAmount()));
            }
            totalMoney = totalMoney.setScale(2, RoundingMode.HALF_UP);
            hhOrder.setTotalMoney(totalMoney.toString());
            hhOrder.setOrderStatus(ParamsDictUtil.ORDER_STATUS_PRINT);
            hhOrderMapper.updateHhOrder(hhOrder);
            //更新用户余额
            HhUser hhUser = hhUserMapper.selectHhUserById(hhOrder.getConsumerId());
            BigDecimal beforeBalance = new BigDecimal(hhUser.getUserAccount()).setScale(2, RoundingMode.HALF_UP);
            BigDecimal afterBalance = null;
            String remark = null;
            String evenId = null;
            if (ParamsDictUtil.ORDER_TYPE_SALE.equals(orderType)) {
                afterBalance = beforeBalance.add(totalMoney).setScale(2, RoundingMode.HALF_UP);
                evenId = ParamsDictUtil.ACCOUNT_INCREASE;
                remark = "销售单";
            } else if (ParamsDictUtil.ORDER_TYPE_RETURN.equals(orderType)) {
                afterBalance = beforeBalance.subtract(totalMoney).setScale(2, RoundingMode.HALF_UP);
                evenId = ParamsDictUtil.ACCOUNT_REDUCE;
                remark = "退货单";
            }
            hhUser.setUserAccount(afterBalance.toString());
            hhUser.setSelectCount(hhUser.getSelectCount());
            hhUserMapper.updateHhUserDetail(hhUser);
            //更新账户变动记录
            HhUserAccount hhUserAccount = new HhUserAccount();
            hhUserAccount.setUserId(hhOrder.getConsumerId());
            hhUserAccount.setBeforeBalance(beforeBalance.toString());
            hhUserAccount.setThisAmount(totalMoney.toString());
            hhUserAccount.setAfterBalance(afterBalance.toString());
            hhUserAccount.setEvenId(evenId);
            hhUserAccount.setOrderId(orderId);
            hhUserAccount.setRemark(remark);
            hhUserAccount.setOperateTime(new Date());
            hhUserAccountMapper.insertHhUserAccount(hhUserAccount);
            resultMap.put("beforeBalance", "￥" + beforeBalance.toString());
            resultMap.put("afterBalance", "￥" + afterBalance.toString());
            log.info("===========变动信息======" + JSON.toJSON(resultMap).toString());
            //查找暂付记录
            hhUserAccount.setEvenId(ParamsDictUtil.ACCOUNT_REDUCE);
            hhUserAccount.setRemark(ParamsDictUtil.REMARK_PAY_NO_PRINT);
            hhUserAccount.setOrderId("");
            List<HhUserAccount> hhUserAccountList = hhUserAccountMapper.selectHhUserAccountList(hhUserAccount);
            if (null != hhUserAccountList && hhUserAccountList.size() > 0) {
                BigDecimal thisAmount = BigDecimal.ZERO;
                String oldestBalance = null;
                Long minUaId = null;
                for (HhUserAccount item : hhUserAccountList) {
                    if (null == minUaId || minUaId > item.getUaId()) {
                        minUaId = item.getUaId();
                        oldestBalance = item.getBeforeBalance();
                    }
                    thisAmount = thisAmount.add(new BigDecimal(item.getThisAmount()));
                    item.setRemark(ParamsDictUtil.REMARK_PAY_PRINT);
                    item.setOrderId(orderId);
                    hhUserAccountMapper.updateHhUserAccount(item);
                }
                resultMap.put("beforeBalance", "￥" + oldestBalance);
                resultMap.put("thisPay", "￥" + thisAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
            }
        }
        //返回打印信息
        resultMap.put("hhOrder", hhOrder);
        resultMap.put("totalMoney", "￥" + hhOrder.getTotalMoney());
        resultMap.put("pageList", PrintPageUtil.printPage(list));
        log.info("===========打印信息======" + JSON.toJSON(resultMap).toString());
        log.info("===============打印日志 end==============");
        return resultMap;
    }

}
